---
- name: "Playbook for deploy flask-app in docker container by docker-compose"
  hosts: node01
  become: true

  vars:
    path_directory_app: /app
    # for Certificate
    country_name: RU
    organization_name: IT-Planeta
    site_name: flask.itplaneta.champ

  roles:
    - docker
    - docker-compose

  tasks:
    - name: "Creating a directory for the application"
      ansible.builtin.file:
        path: "{{ path_directory_app }}"
        state: "directory"

    - name: "Copy the files necessary to run the application"
      ansible.builtin.copy:
        src: "{{ item }}"
        dest: "{{ path_directory_app }}"
      with_items:
        - "flask-app"
        - "www-data"
        - "Dockerfile"
        - "docker-compose.yaml"

    - name: "Install module pip"
      ansible.builtin.apt:
        name:
          - "python3-pip"
          - "python3-setuptools"

    - name: "Install docker module for python"
      ansible.builtin.pip:
        name:
          - "docker==6.1.3"
          - "docker-compose"

    - name: "Generate an OpenSSL private key"
      community.crypto.openssl_privatekey:
        path: "{{ path_directory_app }}/www-data/flask.key"
        size: 4096

    - name: "Generate an OpenSSL Certificate Signing Request"
      community.crypto.openssl_csr:
        path: "{{ path_directory_app }}/www-data/flask.csr"
        privatekey_path: "{{ path_directory_app }}/www-data/flask.key"
        country_name: "{{ country_name }}"
        organization_name: "{{ organization_name }}"
        common_name: "{{ site_name }}"

    - name: "Generate a Self Signed OpenSSL certificate"
      openssl_certificate:
        path: "{{ path_directory_app }}/www-data/flask.crt"
        privatekey_path: "{{ path_directory_app }}/www-data/flask.key"
        csr_path: "{{ path_directory_app }}/www-data/flask.csr"
        provider: selfsigned

# fixed error: "cgroups: cannot found cgroup mount destination: unknown"
    - name: "Create directory /sys/fs/cgroup/systemd"
      ansible.builtin.file:
        path: /sys/fs/cgroup/systemd
        state: "directory"

    - name: "Mount cgroup /sys/fs/cgroup/systemd"
      command:
        cmd: "mount -t cgroup -o none,name=systemd cgroup /sys/fs/cgroup/systemd"
      ignore_errors: true
########################################################################        

    - name: "We launch applications using docker-compose"
      community.docker.docker_compose:
        project_src: "{{ path_directory_app }}"
        files:
          - "docker-compose.yaml"